package tako.wisers.com.android.apis.activity;

import tako.wisers.com.android.apis.R;
import tako.wisers.com.android.apis.item.SettingItem;
import tako.wisers.com.android.apis.preference.ConfDownLoadPreference;
import tako.wisers.com.android.apis.preference.DownLoadPreference;
import tako.wisers.com.android.apis.setting.SettingManager;
import tako.wisers.com.android.apis.util.Global;
import android.content.Intent;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.Preference.OnPreferenceChangeListener;
import android.view.KeyEvent;

public class PreferenceInfoActivity extends PreferenceActivity {
	private SettingManager mSettingManager;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSettingManager = SettingManager.getInstance();
		addPreferencesFromResource(R.xml.preferences);
		
		initConfSetting();
	}

	private void initConfSetting() {
		PreferenceCategory confCategory = (PreferenceCategory) findPreference(Global.CONF_ROOT_PREFERENCE);
		EditTextPreference confEdit = (EditTextPreference) findPreference(Global.CONF_EDITOR_PREFERENCE);
		ConfDownLoadPreference confPre = new ConfDownLoadPreference(this);
		SettingItem confItem = mSettingManager.get(Global.CONF_DOWNLOAD_TYPE);
		confEdit.setText(confItem.getHost());
		confEdit.setOnPreferenceChangeListener(new PreferenceChangeListener(Global.CONF_DOWNLOAD_TYPE, confPre));
		confCategory.addPreference(confPre);
	}
	
	class PreferenceChangeListener implements OnPreferenceChangeListener{
		private int type;
		private DownLoadPreference mPre;
		
		public PreferenceChangeListener(int type, DownLoadPreference pre){
			this.type = type;
			this.mPre = pre;
		}

		@Override
		public boolean onPreferenceChange(Preference preference, Object newValue) {
			String text = newValue.toString();
			SettingItem setting = mSettingManager.get(type);
			setting.setHost(text);
			mSettingManager.updateSetting(setting);
			mPre.execute();
			return true;
		}
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			Intent intent = new Intent();
			intent.setClass(this, Tako.class);
			System.gc();
			startActivity(intent);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
